package com.ruoyi.blog.task;

import com.ruoyi.blog.domain.vo.ResultArticleListVo;
import com.ruoyi.blog.service.IBlogArticleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 更新阅读访问量定时任务
 */
@Configuration
@EnableScheduling
public class RedisArticleViewTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisArticleViewTask.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IBlogArticleService iBlogArticleService;

    // 每隔五分钟进行任务检测
    @Scheduled(cron = "0 */5 * * * ?")
    public void configureTask() {
        LOGGER.debug("定时任务执行啦！！");
        // 读取数据库
        List<ResultArticleListVo> listVoList = iBlogArticleService.selectBlogArticleList();
        for (ResultArticleListVo result : listVoList){
            String key = "article:"+result.getId();
            if (redisTemplate.hasKey(key) ){
                int number = Integer.parseInt(redisTemplate.opsForValue().get(key));
                if (number > 0){
                    iBlogArticleService.incrArticleViewCount(number, result.getId() );
                    // 去掉缓存数据
                    redisTemplate.opsForValue().decrement(key, number);
                }
            }
        }
    }
}
